﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using App.Account.Services;
using StructureMap;
using App.Utility.Services;
using App.Account.Models;
using App.Utility.Paging;
using App.Utility.StateContainers;
using System.Web.Caching;

namespace App.Account.HttpModules
{
    public class RoleAuthenticationModule : IHttpModule
    {
        static Cache Cache { get { return HttpContext.Current.Cache; } }

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
        }

        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current != null)
                    if (HttpContext.Current.User != null)
                    {
                        System.Security.Principal.IIdentity userId =
                            HttpContext.Current.User.Identity;

                        string key = userId.Name + "Roles";

                        if(Cache[key]==null)
                        {
                            using (IAccountService service = ObjectFactory.GetInstance<IAccountService>())
                            {
                                ServiceResponse<User> response = service.GetUserByName(userId.Name);

                                if (response.Successful)
                                {
                                    Cache[key] = (from r in response.Response.Roles select r.Name).ToArray();
                                }
                            }
                        }

                        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
                            userId, (string[])Cache[key]);
                    }
        }

    }
}
